<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>18.5.3. Tasks and coroutines &mdash; Python 3.4.3 documentation</title>
    
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.4.3',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.4.3 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 3.4.3 documentation" href="../index.html" />
    <link rel="up" title="18.5. asyncio – Asynchronous I/O, event loop, coroutines and tasks" href="asyncio.html" />
    <link rel="next" title="18.5.4. Transports and protocols (low-level API)" href="asyncio-protocol.html" />
    <link rel="prev" title="18.5.2. Event loops" href="asyncio-eventloops.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    <script type="text/javascript" src="../_static/version_switch.js"></script>
    
 

  </head>
  <body>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="asyncio-protocol.html" title="18.5.4. Transports and protocols (low-level API)"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="asyncio-eventloops.html" title="18.5.2. Event loops"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
        <li>
          <span class="version_switcher_placeholder">3.4.3</span>
          <a href="../index.html">Documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="ipc.html" >18. Interprocess Communication and Networking</a> &raquo;</li>
          <li><a href="asyncio.html" accesskey="U">18.5. <tt class="docutils literal"><span class="pre">asyncio</span></tt> &#8211; Asynchronous I/O, event loop, coroutines and tasks</a> &raquo;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="tasks-and-coroutines">
<h1>18.5.3. Tasks and coroutines<a class="headerlink" href="#tasks-and-coroutines" title="Permalink to this headline">¶</a></h1>
<div class="section" id="coroutines">
<span id="coroutine"></span><h2>18.5.3.1. Coroutines<a class="headerlink" href="#coroutines" title="Permalink to this headline">¶</a></h2>
<p>A coroutine is a generator that follows certain conventions.  For
documentation purposes, all coroutines should be decorated with
<tt class="docutils literal"><span class="pre">&#64;asyncio.coroutine</span></tt>, but this cannot be strictly enforced.</p>
<p>Coroutines use the <tt class="docutils literal"><span class="pre">yield</span> <span class="pre">from</span></tt> syntax introduced in <span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0380"><strong>PEP 380</strong></a>,
instead of the original <tt class="docutils literal"><span class="pre">yield</span></tt> syntax.</p>
<p>The word &#8220;coroutine&#8221;, like the word &#8220;generator&#8221;, is used for two
different (though related) concepts:</p>
<ul class="simple">
<li>The function that defines a coroutine (a function definition
decorated with <tt class="docutils literal"><span class="pre">&#64;asyncio.coroutine</span></tt>).  If disambiguation is needed
we will call this a <em>coroutine function</em> (<a class="reference internal" href="#asyncio.iscoroutinefunction" title="asyncio.iscoroutinefunction"><tt class="xref py py-func docutils literal"><span class="pre">iscoroutinefunction()</span></tt></a>
returns <tt class="docutils literal"><span class="pre">True</span></tt>).</li>
<li>The object obtained by calling a coroutine function.  This object
represents a computation or an I/O operation (usually a combination)
that will complete eventually.  If disambiguation is needed we will
call it a <em>coroutine object</em> (<a class="reference internal" href="#asyncio.iscoroutine" title="asyncio.iscoroutine"><tt class="xref py py-func docutils literal"><span class="pre">iscoroutine()</span></tt></a> returns <tt class="docutils literal"><span class="pre">True</span></tt>).</li>
</ul>
<p>Things a coroutine can do:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">from</span> <span class="pre">future</span></tt> &#8211; suspends the coroutine until the
future is done, then returns the future&#8217;s result, or raises an
exception, which will be propagated.  (If the future is cancelled,
it will raise a <tt class="docutils literal"><span class="pre">CancelledError</span></tt> exception.)  Note that tasks are
futures, and everything said about futures also applies to tasks.</li>
<li><tt class="docutils literal"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">from</span> <span class="pre">coroutine</span></tt> &#8211; wait for another coroutine to
produce a result (or raise an exception, which will be propagated).
The <tt class="docutils literal"><span class="pre">coroutine</span></tt> expression must be a <em>call</em> to another coroutine.</li>
<li><tt class="docutils literal"><span class="pre">return</span> <span class="pre">expression</span></tt> &#8211; produce a result to the coroutine that is
waiting for this one using <tt class="docutils literal"><span class="pre">yield</span> <span class="pre">from</span></tt>.</li>
<li><tt class="docutils literal"><span class="pre">raise</span> <span class="pre">exception</span></tt> &#8211; raise an exception in the coroutine that is
waiting for this one using <tt class="docutils literal"><span class="pre">yield</span> <span class="pre">from</span></tt>.</li>
</ul>
<p>Calling a coroutine does not start its code running &#8211; it is just a
generator, and the coroutine object returned by the call is really a
generator object, which doesn&#8217;t do anything until you iterate over it.
In the case of a coroutine object, there are two basic ways to start
it running: call <tt class="docutils literal"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre">coroutine</span></tt> from another coroutine
(assuming the other coroutine is already running!), or schedule its execution
using the <a class="reference internal" href="#asyncio.async" title="asyncio.async"><tt class="xref py py-func docutils literal"><span class="pre">async()</span></tt></a> function or the <a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.create_task" title="asyncio.BaseEventLoop.create_task"><tt class="xref py py-meth docutils literal"><span class="pre">BaseEventLoop.create_task()</span></tt></a>
method.</p>
<p>Coroutines (and tasks) can only run when the event loop is running.</p>
<dl class="function">
<dt id="asyncio.coroutine">
<tt class="descclassname">&#64;</tt><tt class="descclassname">asyncio.</tt><tt class="descname">coroutine</tt><a class="headerlink" href="#asyncio.coroutine" title="Permalink to this definition">¶</a></dt>
<dd><p>Decorator to mark coroutines.</p>
<p>If the coroutine is not yielded from before it is destroyed, an error
message is logged. See <a class="reference internal" href="asyncio-dev.html#asyncio-coroutine-not-scheduled"><em>Detect coroutines never scheduled</em></a>.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In this documentation, some methods are documented as coroutines,
even if they are plain Python functions returning a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><tt class="xref py py-class docutils literal"><span class="pre">Future</span></tt></a>.
This is intentional to have a freedom of tweaking the implementation
of these functions in the future. If such a function is needed to be
used in a callback-style code, wrap its result with <a class="reference internal" href="#asyncio.async" title="asyncio.async"><tt class="xref py py-func docutils literal"><span class="pre">async()</span></tt></a>.</p>
</div>
<div class="section" id="example-hello-world-coroutine">
<span id="asyncio-hello-world-coroutine"></span><h3>18.5.3.1.1. Example: Hello World coroutine<a class="headerlink" href="#example-hello-world-coroutine" title="Permalink to this headline">¶</a></h3>
<p>Example of coroutine displaying <tt class="docutils literal"><span class="pre">&quot;Hello</span> <span class="pre">World&quot;</span></tt>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="nd">@asyncio</span><span class="o">.</span><span class="n">coroutine</span>
<span class="k">def</span> <span class="nf">hello_world</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;Hello World!&quot;</span><span class="p">)</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="c"># Blocking call which returns when the hello_world() coroutine is done</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">hello_world</span><span class="p">())</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference internal" href="asyncio-eventloop.html#asyncio-hello-world-callback"><em>Hello World with call_soon()</em></a>
example uses the <a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.call_soon" title="asyncio.BaseEventLoop.call_soon"><tt class="xref py py-meth docutils literal"><span class="pre">BaseEventLoop.call_soon()</span></tt></a> method to schedule a
callback.</p>
</div>
</div>
<div class="section" id="example-coroutine-displaying-the-current-date">
<span id="asyncio-date-coroutine"></span><h3>18.5.3.1.2. Example: Coroutine displaying the current date<a class="headerlink" href="#example-coroutine-displaying-the-current-date" title="Permalink to this headline">¶</a></h3>
<p>Example of coroutine displaying the current date every second during 5 seconds
using the <a class="reference internal" href="#asyncio.sleep" title="asyncio.sleep"><tt class="xref py py-meth docutils literal"><span class="pre">sleep()</span></tt></a> function:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">datetime</span>

<span class="nd">@asyncio</span><span class="o">.</span><span class="n">coroutine</span>
<span class="k">def</span> <span class="nf">display_date</span><span class="p">(</span><span class="n">loop</span><span class="p">):</span>
    <span class="n">end_time</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">5.0</span>
    <span class="k">while</span> <span class="k">True</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">1.0</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="n">end_time</span><span class="p">:</span>
            <span class="k">break</span>
        <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="c"># Blocking call which returns when the display_date() coroutine is done</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">display_date</span><span class="p">(</span><span class="n">loop</span><span class="p">))</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference internal" href="asyncio-eventloop.html#asyncio-date-callback"><em>display the current date with call_later()</em></a> example uses a callback with the
<a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.call_later" title="asyncio.BaseEventLoop.call_later"><tt class="xref py py-meth docutils literal"><span class="pre">BaseEventLoop.call_later()</span></tt></a> method.</p>
</div>
</div>
<div class="section" id="example-chain-coroutines">
<h3>18.5.3.1.3. Example: Chain coroutines<a class="headerlink" href="#example-chain-coroutines" title="Permalink to this headline">¶</a></h3>
<p>Example chaining coroutines:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="nd">@asyncio</span><span class="o">.</span><span class="n">coroutine</span>
<span class="k">def</span> <span class="nf">compute</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;Compute %s + %s ...&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">))</span>
    <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">1.0</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>

<span class="nd">@asyncio</span><span class="o">.</span><span class="n">coroutine</span>
<span class="k">def</span> <span class="nf">print_sum</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="n">result</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">compute</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;%s + %s = %s&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">result</span><span class="p">))</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">print_sum</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">compute()</span></tt> is chained to <tt class="docutils literal"><span class="pre">print_sum()</span></tt>: <tt class="docutils literal"><span class="pre">print_sum()</span></tt> coroutine waits
until <tt class="docutils literal"><span class="pre">compute()</span></tt> is completed before returning its result.</p>
<p>Sequence diagram of the example:</p>
<img alt="../_images/tulip_coro.png" class="align-center" src="../_images/tulip_coro.png" />
<p>The &#8220;Task&#8221; is created by the <a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.run_until_complete" title="asyncio.BaseEventLoop.run_until_complete"><tt class="xref py py-meth docutils literal"><span class="pre">BaseEventLoop.run_until_complete()</span></tt></a> method
when it gets a coroutine object instead of a task.</p>
<p>The diagram shows the control flow, it does not describe exactly how things
work internally. For example, the sleep coroutine creates an internal future
which uses <a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.call_later" title="asyncio.BaseEventLoop.call_later"><tt class="xref py py-meth docutils literal"><span class="pre">BaseEventLoop.call_later()</span></tt></a> to wake up the task in 1 second.</p>
</div>
</div>
<div class="section" id="invalidstateerror">
<h2>18.5.3.2. InvalidStateError<a class="headerlink" href="#invalidstateerror" title="Permalink to this headline">¶</a></h2>
<dl class="exception">
<dt id="asyncio.InvalidStateError">
<em class="property">exception </em><tt class="descclassname">asyncio.</tt><tt class="descname">InvalidStateError</tt><a class="headerlink" href="#asyncio.InvalidStateError" title="Permalink to this definition">¶</a></dt>
<dd><p>The operation is not allowed in this state.</p>
</dd></dl>

</div>
<div class="section" id="timeouterror">
<h2>18.5.3.3. TimeoutError<a class="headerlink" href="#timeouterror" title="Permalink to this headline">¶</a></h2>
<dl class="exception">
<dt id="asyncio.TimeoutError">
<em class="property">exception </em><tt class="descclassname">asyncio.</tt><tt class="descname">TimeoutError</tt><a class="headerlink" href="#asyncio.TimeoutError" title="Permalink to this definition">¶</a></dt>
<dd><p>The operation exceeded the given deadline.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This exception is different from the builtin <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><tt class="xref py py-exc docutils literal"><span class="pre">TimeoutError</span></tt></a> exception!</p>
</div>
</div>
<div class="section" id="future">
<h2>18.5.3.4. Future<a class="headerlink" href="#future" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="asyncio.Future">
<em class="property">class </em><tt class="descclassname">asyncio.</tt><tt class="descname">Future</tt><big>(</big><em>*</em>, <em>loop=None</em><big>)</big><a class="headerlink" href="#asyncio.Future" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is <em>almost</em> compatible with <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><tt class="xref py py-class docutils literal"><span class="pre">concurrent.futures.Future</span></tt></a>.</p>
<p>Differences:</p>
<ul class="simple">
<li><a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><tt class="xref py py-meth docutils literal"><span class="pre">result()</span></tt></a> and <a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><tt class="xref py py-meth docutils literal"><span class="pre">exception()</span></tt></a> do not take a timeout argument and
raise an exception when the future isn&#8217;t done yet.</li>
<li>Callbacks registered with <a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><tt class="xref py py-meth docutils literal"><span class="pre">add_done_callback()</span></tt></a> are always called
via the event loop&#8217;s <a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.call_soon_threadsafe" title="asyncio.BaseEventLoop.call_soon_threadsafe"><tt class="xref py py-meth docutils literal"><span class="pre">call_soon_threadsafe()</span></tt></a>.</li>
<li>This class is not compatible with the <a class="reference internal" href="concurrent.futures.html#concurrent.futures.wait" title="concurrent.futures.wait"><tt class="xref py py-func docutils literal"><span class="pre">wait()</span></tt></a> and
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.as_completed" title="concurrent.futures.as_completed"><tt class="xref py py-func docutils literal"><span class="pre">as_completed()</span></tt></a> functions in the
<a class="reference internal" href="concurrent.futures.html#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><tt class="xref py py-mod docutils literal"><span class="pre">concurrent.futures</span></tt></a> package.</li>
</ul>
<p>This class is <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><em>not thread safe</em></a>.</p>
<dl class="method">
<dt id="asyncio.Future.cancel">
<tt class="descname">cancel</tt><big>(</big><big>)</big><a class="headerlink" href="#asyncio.Future.cancel" title="Permalink to this definition">¶</a></dt>
<dd><p>Cancel the future and schedule callbacks.</p>
<p>If the future is already done or cancelled, return <tt class="docutils literal"><span class="pre">False</span></tt>. Otherwise,
change the future&#8217;s state to cancelled, schedule the callbacks and return
<tt class="docutils literal"><span class="pre">True</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.cancelled">
<tt class="descname">cancelled</tt><big>(</big><big>)</big><a class="headerlink" href="#asyncio.Future.cancelled" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if the future was cancelled.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.done">
<tt class="descname">done</tt><big>(</big><big>)</big><a class="headerlink" href="#asyncio.Future.done" title="Permalink to this definition">¶</a></dt>
<dd><p>Return True if the future is done.</p>
<p>Done means either that a result / exception are available, or that the
future was cancelled.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.result">
<tt class="descname">result</tt><big>(</big><big>)</big><a class="headerlink" href="#asyncio.Future.result" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the result this future represents.</p>
<p>If the future has been cancelled, raises <tt class="xref py py-exc docutils literal"><span class="pre">CancelledError</span></tt>. If the
future&#8217;s result isn&#8217;t yet available, raises <a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><tt class="xref py py-exc docutils literal"><span class="pre">InvalidStateError</span></tt></a>. If
the future is done and has an exception set, this exception is raised.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.exception">
<tt class="descname">exception</tt><big>(</big><big>)</big><a class="headerlink" href="#asyncio.Future.exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the exception that was set on this future.</p>
<p>The exception (or <tt class="docutils literal"><span class="pre">None</span></tt> if no exception was set) is returned only if
the future is done. If the future has been cancelled, raises
<tt class="xref py py-exc docutils literal"><span class="pre">CancelledError</span></tt>. If the future isn&#8217;t done yet, raises
<a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><tt class="xref py py-exc docutils literal"><span class="pre">InvalidStateError</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.add_done_callback">
<tt class="descname">add_done_callback</tt><big>(</big><em>fn</em><big>)</big><a class="headerlink" href="#asyncio.Future.add_done_callback" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a callback to be run when the future becomes done.</p>
<p>The callback is called with a single argument - the future object. If the
future is already done when this is called, the callback is scheduled
with <a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.call_soon" title="asyncio.BaseEventLoop.call_soon"><tt class="xref py py-meth docutils literal"><span class="pre">call_soon()</span></tt></a>.</p>
<p><a class="reference internal" href="asyncio-eventloop.html#asyncio-pass-keywords"><em>Use functools.partial to pass parameters to the callback</em></a>. For example,
<tt class="docutils literal"><span class="pre">fut.add_done_callback(functools.partial(print,</span> <span class="pre">&quot;Future:&quot;,</span>
<span class="pre">flush=True))</span></tt> will call <tt class="docutils literal"><span class="pre">print(&quot;Future:&quot;,</span> <span class="pre">fut,</span> <span class="pre">flush=True)</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.remove_done_callback">
<tt class="descname">remove_done_callback</tt><big>(</big><em>fn</em><big>)</big><a class="headerlink" href="#asyncio.Future.remove_done_callback" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove all instances of a callback from the &#8220;call when done&#8221; list.</p>
<p>Returns the number of callbacks removed.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.set_result">
<tt class="descname">set_result</tt><big>(</big><em>result</em><big>)</big><a class="headerlink" href="#asyncio.Future.set_result" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark the future done and set its result.</p>
<p>If the future is already done when this method is called, raises
<a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><tt class="xref py py-exc docutils literal"><span class="pre">InvalidStateError</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.set_exception">
<tt class="descname">set_exception</tt><big>(</big><em>exception</em><big>)</big><a class="headerlink" href="#asyncio.Future.set_exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark the future done and set an exception.</p>
<p>If the future is already done when this method is called, raises
<a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><tt class="xref py py-exc docutils literal"><span class="pre">InvalidStateError</span></tt></a>.</p>
</dd></dl>

</dd></dl>

<div class="section" id="example-future-with-run-until-complete">
<h3>18.5.3.4.1. Example: Future with run_until_complete()<a class="headerlink" href="#example-future-with-run-until-complete" title="Permalink to this headline">¶</a></h3>
<p>Example combining a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><tt class="xref py py-class docutils literal"><span class="pre">Future</span></tt></a> and a <a class="reference internal" href="#coroutine"><em>coroutine function</em></a>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="nd">@asyncio</span><span class="o">.</span><span class="n">coroutine</span>
<span class="k">def</span> <span class="nf">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">):</span>
    <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">future</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="s">&#39;Future is done!&#39;</span><span class="p">)</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Future</span><span class="p">()</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">))</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">future</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">())</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The coroutine function is responsible for the computation (which takes 1 second)
and it stores the result into the future. The
<a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.run_until_complete" title="asyncio.BaseEventLoop.run_until_complete"><tt class="xref py py-meth docutils literal"><span class="pre">run_until_complete()</span></tt></a> method waits for the completion of
the future.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.run_until_complete" title="asyncio.BaseEventLoop.run_until_complete"><tt class="xref py py-meth docutils literal"><span class="pre">run_until_complete()</span></tt></a> method uses internally the
<a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><tt class="xref py py-meth docutils literal"><span class="pre">add_done_callback()</span></tt></a> method to be notified when the future is
done.</p>
</div>
</div>
<div class="section" id="example-future-with-run-forever">
<h3>18.5.3.4.2. Example: Future with run_forever()<a class="headerlink" href="#example-future-with-run-forever" title="Permalink to this headline">¶</a></h3>
<p>The previous example can be written differently using the
<a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><tt class="xref py py-meth docutils literal"><span class="pre">Future.add_done_callback()</span></tt></a> method to describe explicitly the control
flow:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="nd">@asyncio</span><span class="o">.</span><span class="n">coroutine</span>
<span class="k">def</span> <span class="nf">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">):</span>
    <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">future</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="s">&#39;Future is done!&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">got_result</span><span class="p">(</span><span class="n">future</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">())</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Future</span><span class="p">()</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">))</span>
<span class="n">future</span><span class="o">.</span><span class="n">add_done_callback</span><span class="p">(</span><span class="n">got_result</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>In this example, the future is used to link <tt class="docutils literal"><span class="pre">slow_operation()</span></tt> to
<tt class="docutils literal"><span class="pre">got_result()</span></tt>: when <tt class="docutils literal"><span class="pre">slow_operation()</span></tt> is done, <tt class="docutils literal"><span class="pre">got_result()</span></tt> is called
with the result.</p>
</div>
</div>
<div class="section" id="task">
<h2>18.5.3.5. Task<a class="headerlink" href="#task" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="asyncio.Task">
<em class="property">class </em><tt class="descclassname">asyncio.</tt><tt class="descname">Task</tt><big>(</big><em>coro</em>, <em>*</em>, <em>loop=None</em><big>)</big><a class="headerlink" href="#asyncio.Task" title="Permalink to this definition">¶</a></dt>
<dd><p>Schedule the execution of a <a class="reference internal" href="#coroutine"><em>coroutine</em></a>: wrap it in a
future. A task is a subclass of <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><tt class="xref py py-class docutils literal"><span class="pre">Future</span></tt></a>.</p>
<p>A task is responsible for executing a coroutine object in an event loop.  If
the wrapped coroutine yields from a future, the task suspends the execution
of the wrapped coroutine and waits for the completition of the future. When
the future is done, the execution of the wrapped coroutine restarts with the
result or the exception of the future.</p>
<p>Event loops use cooperative scheduling: an event loop only runs one task at
a time. Other tasks may run in parallel if other event loops are
running in different threads. While a task waits for the completion of a
future, the event loop executes a new task.</p>
<p>The cancellation of a task is different from the cancelation of a future. Calling
<a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><tt class="xref py py-meth docutils literal"><span class="pre">cancel()</span></tt></a> will throw a <tt class="xref py py-exc docutils literal"><span class="pre">CancelledError</span></tt> to the
wrapped coroutine. <a class="reference internal" href="#asyncio.Future.cancelled" title="asyncio.Future.cancelled"><tt class="xref py py-meth docutils literal"><span class="pre">cancelled()</span></tt></a> only returns <tt class="docutils literal"><span class="pre">True</span></tt> if the
wrapped coroutine did not catch the
<tt class="xref py py-exc docutils literal"><span class="pre">CancelledError</span></tt> exception, or raised a
<tt class="xref py py-exc docutils literal"><span class="pre">CancelledError</span></tt> exception.</p>
<p>If a pending task is destroyed, the execution of its wrapped <a class="reference internal" href="#coroutine"><em>coroutine</em></a> did not complete. It is probably a bug and a warning is
logged: see <a class="reference internal" href="asyncio-dev.html#asyncio-pending-task-destroyed"><em>Pending task destroyed</em></a>.</p>
<p>Don&#8217;t directly create <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><tt class="xref py py-class docutils literal"><span class="pre">Task</span></tt></a> instances: use the <a class="reference internal" href="#asyncio.async" title="asyncio.async"><tt class="xref py py-func docutils literal"><span class="pre">async()</span></tt></a>
function or the <a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.create_task" title="asyncio.BaseEventLoop.create_task"><tt class="xref py py-meth docutils literal"><span class="pre">BaseEventLoop.create_task()</span></tt></a> method.</p>
<p>This class is <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><em>not thread safe</em></a>.</p>
<dl class="classmethod">
<dt id="asyncio.Task.all_tasks">
<em class="property">classmethod </em><tt class="descname">all_tasks</tt><big>(</big><em>loop=None</em><big>)</big><a class="headerlink" href="#asyncio.Task.all_tasks" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a set of all tasks for an event loop.</p>
<p>By default all tasks for the current event loop are returned.</p>
</dd></dl>

<dl class="classmethod">
<dt id="asyncio.Task.current_task">
<em class="property">classmethod </em><tt class="descname">current_task</tt><big>(</big><em>loop=None</em><big>)</big><a class="headerlink" href="#asyncio.Task.current_task" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the currently running task in an event loop or <tt class="docutils literal"><span class="pre">None</span></tt>.</p>
<p>By default the current task for the current event loop is returned.</p>
<p><tt class="docutils literal"><span class="pre">None</span></tt> is returned when called not in the context of a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><tt class="xref py py-class docutils literal"><span class="pre">Task</span></tt></a>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Task.cancel">
<tt class="descname">cancel</tt><big>(</big><big>)</big><a class="headerlink" href="#asyncio.Task.cancel" title="Permalink to this definition">¶</a></dt>
<dd><p>Request that this task cancel itself.</p>
<p>This arranges for a <tt class="xref py py-exc docutils literal"><span class="pre">CancelledError</span></tt> to be
thrown into the wrapped coroutine on the next cycle through the event
loop. The coroutine then has a chance to clean up or even deny the
request using try/except/finally.</p>
<p>Unlike <a class="reference internal" href="#asyncio.Future.cancel" title="asyncio.Future.cancel"><tt class="xref py py-meth docutils literal"><span class="pre">Future.cancel()</span></tt></a>, this does not guarantee that the task
will be cancelled: the exception might be caught and acted upon, delaying
cancellation of the task or preventing cancellation completely. The task
may also return a value or raise a different exception.</p>
<p>Immediately after this method is called, <a class="reference internal" href="#asyncio.Future.cancelled" title="asyncio.Future.cancelled"><tt class="xref py py-meth docutils literal"><span class="pre">cancelled()</span></tt></a> will
not return <tt class="docutils literal"><span class="pre">True</span></tt> (unless the task was already cancelled). A task will
be marked as cancelled when the wrapped coroutine terminates with a
<tt class="xref py py-exc docutils literal"><span class="pre">CancelledError</span></tt> exception (even if
<a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><tt class="xref py py-meth docutils literal"><span class="pre">cancel()</span></tt></a> was not called).</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Task.get_stack">
<tt class="descname">get_stack</tt><big>(</big><em>*</em>, <em>limit=None</em><big>)</big><a class="headerlink" href="#asyncio.Task.get_stack" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the list of stack frames for this task&#8217;s coroutine.</p>
<p>If the coroutine is not done, this returns the stack where it is suspended.
If the coroutine has completed successfully or was cancelled, this
returns an empty list.  If the coroutine was terminated by an exception,
this returns the list of traceback frames.</p>
<p>The frames are always ordered from oldest to newest.</p>
<p>The optional limit gives the maximum number of frames to return; by
default all available frames are returned.  Its meaning differs depending
on whether a stack or a traceback is returned: the newest frames of a
stack are returned, but the oldest frames of a traceback are returned.
(This matches the behavior of the traceback module.)</p>
<p>For reasons beyond our control, only one stack frame is returned for a
suspended coroutine.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Task.print_stack">
<tt class="descname">print_stack</tt><big>(</big><em>*</em>, <em>limit=None</em>, <em>file=None</em><big>)</big><a class="headerlink" href="#asyncio.Task.print_stack" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the stack or traceback for this task&#8217;s coroutine.</p>
<p>This produces output similar to that of the traceback module, for the
frames retrieved by get_stack().  The limit argument is passed to
get_stack().  The file argument is an I/O stream to which the output
is written; by default output is written to sys.stderr.</p>
</dd></dl>

</dd></dl>

<div class="section" id="example-parallel-execution-of-tasks">
<h3>18.5.3.5.1. Example: Parallel execution of tasks<a class="headerlink" href="#example-parallel-execution-of-tasks" title="Permalink to this headline">¶</a></h3>
<p>Example executing 3 tasks (A, B, C) in parallel:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="nd">@asyncio</span><span class="o">.</span><span class="n">coroutine</span>
<span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">number</span><span class="p">):</span>
    <span class="n">f</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">number</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s">&quot;Task %s: Compute factorial(%s)...&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">i</span><span class="p">))</span>
        <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">f</span> <span class="o">*=</span> <span class="n">i</span>
    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;Task %s: factorial(%s) = %s&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">number</span><span class="p">,</span> <span class="n">f</span><span class="p">))</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">tasks</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">factorial</span><span class="p">(</span><span class="s">&quot;A&quot;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)),</span>
    <span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">factorial</span><span class="p">(</span><span class="s">&quot;B&quot;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)),</span>
    <span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">factorial</span><span class="p">(</span><span class="s">&quot;C&quot;</span><span class="p">,</span> <span class="mi">4</span><span class="p">))]</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">asyncio</span><span class="o">.</span><span class="n">wait</span><span class="p">(</span><span class="n">tasks</span><span class="p">))</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Output:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">Task</span> <span class="n">A</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">B</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">A</span><span class="p">:</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">=</span> <span class="mi">2</span>
<span class="n">Task</span> <span class="n">B</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">B</span><span class="p">:</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="o">=</span> <span class="mi">6</span>
<span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="o">=</span> <span class="mi">24</span>
</pre></div>
</div>
<p>A task is automatically scheduled for execution when it is created. The event
loop stops when all tasks are done.</p>
</div>
</div>
<div class="section" id="task-functions">
<h2>18.5.3.6. Task functions<a class="headerlink" href="#task-functions" title="Permalink to this headline">¶</a></h2>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In the functions below, the optional <em>loop</em> argument allows to explicitly set
the event loop object used by the underlying task or coroutine.  If it&#8217;s
not provided, the default event loop is used.</p>
</div>
<dl class="function">
<dt id="asyncio.as_completed">
<tt class="descclassname">asyncio.</tt><tt class="descname">as_completed</tt><big>(</big><em>fs</em>, <em>*</em>, <em>loop=None</em>, <em>timeout=None</em><big>)</big><a class="headerlink" href="#asyncio.as_completed" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator whose values, when waited for, are <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><tt class="xref py py-class docutils literal"><span class="pre">Future</span></tt></a>
instances.</p>
<p>Raises <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><tt class="xref py py-exc docutils literal"><span class="pre">asyncio.TimeoutError</span></tt></a> if the timeout occurs before all Futures
are done.</p>
<p>Example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">as_completed</span><span class="p">(</span><span class="n">fs</span><span class="p">):</span>
    <span class="n">result</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">f</span>  <span class="c"># The &#39;yield from&#39; may raise</span>
    <span class="c"># Use result</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The futures <tt class="docutils literal"><span class="pre">f</span></tt> are not necessarily members of fs.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.ensure_future">
<tt class="descclassname">asyncio.</tt><tt class="descname">ensure_future</tt><big>(</big><em>coro_or_future</em>, <em>*</em>, <em>loop=None</em><big>)</big><a class="headerlink" href="#asyncio.ensure_future" title="Permalink to this definition">¶</a></dt>
<dd><p>Schedule the execution of a <a class="reference internal" href="#coroutine"><em>coroutine object</em></a>: wrap it in
a future. Return a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><tt class="xref py py-class docutils literal"><span class="pre">Task</span></tt></a> object.</p>
<p>If the argument is a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><tt class="xref py py-class docutils literal"><span class="pre">Future</span></tt></a>, it is returned directly.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 3.4.4.</span></p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference internal" href="asyncio-eventloop.html#asyncio.BaseEventLoop.create_task" title="asyncio.BaseEventLoop.create_task"><tt class="xref py py-meth docutils literal"><span class="pre">BaseEventLoop.create_task()</span></tt></a> method.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.async">
<tt class="descclassname">asyncio.</tt><tt class="descname">async</tt><big>(</big><em>coro_or_future</em>, <em>*</em>, <em>loop=None</em><big>)</big><a class="headerlink" href="#asyncio.async" title="Permalink to this definition">¶</a></dt>
<dd><p>A deprecated alias to <a class="reference internal" href="#asyncio.ensure_future" title="asyncio.ensure_future"><tt class="xref py py-func docutils literal"><span class="pre">ensure_future()</span></tt></a>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 3.4.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.gather">
<tt class="descclassname">asyncio.</tt><tt class="descname">gather</tt><big>(</big><em>*coros_or_futures</em>, <em>loop=None</em>, <em>return_exceptions=False</em><big>)</big><a class="headerlink" href="#asyncio.gather" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a future aggregating results from the given coroutine objects or
futures.</p>
<p>All futures must share the same event loop.  If all the tasks are done
successfully, the returned future&#8217;s result is the list of results (in the
order of the original sequence, not necessarily the order of results
arrival).  If <em>return_exceptions</em> is True, exceptions in the tasks are
treated the same as successful results, and gathered in the result list;
otherwise, the first raised exception will be immediately propagated to the
returned future.</p>
<p>Cancellation: if the outer Future is cancelled, all children (that have not
completed yet) are also cancelled.  If any child is cancelled, this is
treated as if it raised <tt class="xref py py-exc docutils literal"><span class="pre">CancelledError</span></tt> &#8211; the
outer Future is <em>not</em> cancelled in this case.  (This is to prevent the
cancellation of one child to cause other children to be cancelled.)</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.iscoroutine">
<tt class="descclassname">asyncio.</tt><tt class="descname">iscoroutine</tt><big>(</big><em>obj</em><big>)</big><a class="headerlink" href="#asyncio.iscoroutine" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if <em>obj</em> is a <a class="reference internal" href="#coroutine"><em>coroutine object</em></a>.</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.iscoroutinefunction">
<tt class="descclassname">asyncio.</tt><tt class="descname">iscoroutinefunction</tt><big>(</big><em>obj</em><big>)</big><a class="headerlink" href="#asyncio.iscoroutinefunction" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <tt class="docutils literal"><span class="pre">True</span></tt> if <em>func</em> is a decorated <a class="reference internal" href="#coroutine"><em>coroutine function</em></a>.</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.sleep">
<em class="property">coroutine </em><tt class="descclassname">asyncio.</tt><tt class="descname">sleep</tt><big>(</big><em>delay</em>, <em>result=None</em>, <em>*</em>, <em>loop=None</em><big>)</big><a class="headerlink" href="#asyncio.sleep" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#coroutine"><em>coroutine</em></a> that completes after a given
time (in seconds).  If <em>result</em> is provided, it is produced to the caller
when the coroutine completes.</p>
<p>The resolution of the sleep depends on the <a class="reference internal" href="asyncio-eventloop.html#asyncio-delayed-calls"><em>granularity of the event
loop</em></a>.</p>
<p>This function is a <a class="reference internal" href="#coroutine"><em>coroutine</em></a>.</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.shield">
<tt class="descclassname">asyncio.</tt><tt class="descname">shield</tt><big>(</big><em>arg</em>, <em>*</em>, <em>loop=None</em><big>)</big><a class="headerlink" href="#asyncio.shield" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for a future, shielding it from cancellation.</p>
<p>The statement:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">res</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">shield</span><span class="p">(</span><span class="n">something</span><span class="p">())</span>
</pre></div>
</div>
<p>is exactly equivalent to the statement:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">res</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">something</span><span class="p">()</span>
</pre></div>
</div>
<p><em>except</em> that if the coroutine containing it is cancelled, the task running
in <tt class="docutils literal"><span class="pre">something()</span></tt> is not cancelled.  From the point of view of
<tt class="docutils literal"><span class="pre">something()</span></tt>, the cancellation did not happen.  But its caller is still
cancelled, so the yield-from expression still raises
<tt class="xref py py-exc docutils literal"><span class="pre">CancelledError</span></tt>.  Note: If <tt class="docutils literal"><span class="pre">something()</span></tt> is
cancelled by other means this will still cancel <tt class="docutils literal"><span class="pre">shield()</span></tt>.</p>
<p>If you want to completely ignore cancellation (not recommended) you can
combine <tt class="docutils literal"><span class="pre">shield()</span></tt> with a try/except clause, as follows:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
    <span class="n">res</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">shield</span><span class="p">(</span><span class="n">something</span><span class="p">())</span>
<span class="k">except</span> <span class="n">CancelledError</span><span class="p">:</span>
    <span class="n">res</span> <span class="o">=</span> <span class="k">None</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.wait">
<em class="property">coroutine </em><tt class="descclassname">asyncio.</tt><tt class="descname">wait</tt><big>(</big><em>futures</em>, <em>*</em>, <em>loop=None</em>, <em>timeout=None</em>, <em>return_when=ALL_COMPLETED</em><big>)</big><a class="headerlink" href="#asyncio.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for the Futures and coroutine objects given by the sequence <em>futures</em>
to complete.  Coroutines will be wrapped in Tasks. Returns two sets of
<a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><tt class="xref py py-class docutils literal"><span class="pre">Future</span></tt></a>: (done, pending).</p>
<p>The sequence <em>futures</em> must not be empty.</p>
<p><em>timeout</em> can be used to control the maximum number of seconds to wait before
returning.  <em>timeout</em> can be an int or float.  If <em>timeout</em> is not specified
or <tt class="docutils literal"><span class="pre">None</span></tt>, there is no limit to the wait time.</p>
<p><em>return_when</em> indicates when this function should return.  It must be one of
the following constants of the <a class="reference internal" href="concurrent.futures.html#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><tt class="xref py py-mod docutils literal"><span class="pre">concurrent.futures</span></tt></a> module:</p>
<table border="1" class="docutils">
<colgroup>
<col width="42%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><tt class="xref py py-const docutils literal"><span class="pre">FIRST_COMPLETED</span></tt></td>
<td>The function will return when any
future finishes or is cancelled.</td>
</tr>
<tr class="row-odd"><td><tt class="xref py py-const docutils literal"><span class="pre">FIRST_EXCEPTION</span></tt></td>
<td>The function will return when any
future finishes by raising an
exception.  If no future raises an
exception then it is equivalent to
<tt class="xref py py-const docutils literal"><span class="pre">ALL_COMPLETED</span></tt>.</td>
</tr>
<tr class="row-even"><td><tt class="xref py py-const docutils literal"><span class="pre">ALL_COMPLETED</span></tt></td>
<td>The function will return when all
futures finish or are cancelled.</td>
</tr>
</tbody>
</table>
<p>This function is a <a class="reference internal" href="#coroutine"><em>coroutine</em></a>.</p>
<p>Usage:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">done</span><span class="p">,</span> <span class="n">pending</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait</span><span class="p">(</span><span class="n">fs</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This does not raise <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><tt class="xref py py-exc docutils literal"><span class="pre">asyncio.TimeoutError</span></tt></a>! Futures that aren&#8217;t done
when the timeout occurs are returned in the second set.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.wait_for">
<em class="property">coroutine </em><tt class="descclassname">asyncio.</tt><tt class="descname">wait_for</tt><big>(</big><em>fut</em>, <em>timeout</em>, <em>*</em>, <em>loop=None</em><big>)</big><a class="headerlink" href="#asyncio.wait_for" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for the single <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><tt class="xref py py-class docutils literal"><span class="pre">Future</span></tt></a> or <a class="reference internal" href="#coroutine"><em>coroutine object</em></a>
to complete with timeout. If <em>timeout</em> is <tt class="docutils literal"><span class="pre">None</span></tt>, block until the future
completes.</p>
<p>Coroutine will be wrapped in <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><tt class="xref py py-class docutils literal"><span class="pre">Task</span></tt></a>.</p>
<p>Returns result of the Future or coroutine.  When a timeout occurs, it
cancels the task and raises <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><tt class="xref py py-exc docutils literal"><span class="pre">asyncio.TimeoutError</span></tt></a>. To avoid the task
cancellation, wrap it in <a class="reference internal" href="#asyncio.shield" title="asyncio.shield"><tt class="xref py py-func docutils literal"><span class="pre">shield()</span></tt></a>.</p>
<p>If the wait is cancelled, the future <em>fut</em> is also cancelled.</p>
<p>This function is a <a class="reference internal" href="#coroutine"><em>coroutine</em></a>, usage:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">result</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait_for</span><span class="p">(</span><span class="n">fut</span><span class="p">,</span> <span class="mf">60.0</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.4.3: </span>If the wait is cancelled, the future <em>fut</em> is now also cancelled.</p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.5.3. Tasks and coroutines</a><ul>
<li><a class="reference internal" href="#coroutines">18.5.3.1. Coroutines</a><ul>
<li><a class="reference internal" href="#example-hello-world-coroutine">18.5.3.1.1. Example: Hello World coroutine</a></li>
<li><a class="reference internal" href="#example-coroutine-displaying-the-current-date">18.5.3.1.2. Example: Coroutine displaying the current date</a></li>
<li><a class="reference internal" href="#example-chain-coroutines">18.5.3.1.3. Example: Chain coroutines</a></li>
</ul>
</li>
<li><a class="reference internal" href="#invalidstateerror">18.5.3.2. InvalidStateError</a></li>
<li><a class="reference internal" href="#timeouterror">18.5.3.3. TimeoutError</a></li>
<li><a class="reference internal" href="#future">18.5.3.4. Future</a><ul>
<li><a class="reference internal" href="#example-future-with-run-until-complete">18.5.3.4.1. Example: Future with run_until_complete()</a></li>
<li><a class="reference internal" href="#example-future-with-run-forever">18.5.3.4.2. Example: Future with run_forever()</a></li>
</ul>
</li>
<li><a class="reference internal" href="#task">18.5.3.5. Task</a><ul>
<li><a class="reference internal" href="#example-parallel-execution-of-tasks">18.5.3.5.1. Example: Parallel execution of tasks</a></li>
</ul>
</li>
<li><a class="reference internal" href="#task-functions">18.5.3.6. Task functions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="asyncio-eventloops.html"
                        title="previous chapter">18.5.2. Event loops</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="asyncio-protocol.html"
                        title="next chapter">18.5.4. Transports  and protocols (low-level API)</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/library/asyncio-task.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="asyncio-protocol.html" title="18.5.4. Transports and protocols (low-level API)"
             >next</a> |</li>
        <li class="right" >
          <a href="asyncio-eventloops.html" title="18.5.2. Event loops"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &raquo;</li>
        <li>
          <span class="version_switcher_placeholder">3.4.3</span>
          <a href="../index.html">Documentation</a> &raquo;
        </li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="ipc.html" >18. Interprocess Communication and Networking</a> &raquo;</li>
          <li><a href="asyncio.html" >18.5. <tt class="docutils literal"><span class="pre">asyncio</span></tt> &#8211; Asynchronous I/O, event loop, coroutines and tasks</a> &raquo;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2015, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on May 11, 2015.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.3.
    </div>

  </body>
</html>